import {routerRedux} from 'dva/router';
import {stringify} from 'querystring';
import {fakeAccountLogin, getFakeCaptcha, fakeAccountLogout} from '@/services/login';
import {setAuthority} from '@/utils/authority';
import {getPageQuery} from '@/utils/utils';
import {login} from "@/services/user/UserService";
import {message} from "antd";

const Model = {
    namespace: 'login',
    state: {
        status: undefined,
    },
    effects: {

        /**
         * 登录
         */* login({payload, callback}, {call, put}) {
            const response = yield call(fakeAccountLogin, payload);

            if (!response || !response.MYRCIB_USER_TOKEN) {
                message.error('账号错误，登录失败！');
                return;
            }
            sessionStorage.removeItem('UtypeId');
            sessionStorage.removeItem('MYRCIB_USER_TOKEN');
            sessionStorage.setItem('MYRCIB_USER_TOKEN', response.MYRCIB_USER_TOKEN);

            if (response.MYRCIB_USER_TOKEN) {
                yield put({
                    type: 'changeLoginStatus',
                    payload: {
                        status: 'ok',
                        type: "account"
                    }
                });
                window.location.href = "/index";
            }
        },

        * getCaptcha({payload}, {call}) {
            yield call(getFakeCaptcha, payload);
        },


        * logout({payload}, {call, put}) {
            const token = sessionStorage.getItem('MYRCIB_USER_TOKEN');
            if (token) {
                const response = yield call(fakeAccountLogout, payload);
                if (response.success) {
                    sessionStorage.removeItem('MYRCIB_USER_TOKEN');
                }
            }
            yield put({
                type: 'changeLoginStatus',
                payload: {
                    status: false,
                    currentAuthority: 'guest',
                },
            });

            reloadAuthorized();
            yield put(
                routerRedux.push({
                    pathname: '/user/login',
                    search: stringify({
                        redirect: window.location.href,
                    }),
                }),
            );
        },
    },
    reducers: {
        changeLoginStatus(state, {payload}) {
            setAuthority(payload.currentAuthority);
            return {
                ...state,
                status: payload.status,
                type: payload.type,
            };
        },
    },
};
export default Model;
